package com.east.sng.controller;

import com.east.sng.entity.param.UserParam;
import com.east.sng.entity.param.UserPassword;
import com.east.sng.entity.result.EncryptedData;
import com.east.sng.entity.result.UserFind;
import com.east.sng.service.RoleService;
import com.east.sng.service.UserService;
import com.east.sng.utils.EncryptDataUtil;
import com.east.sng.utils.ValidationUtil;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author east
 * @date: 2020/12/27
 * @Description:
 **/
@Validated
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * 用户列表页面跳转
     * @param userName
     * @param roleName
     * @param flag
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @RequiresRoles("0")
    @RequiresPermissions("user:list")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(String userName,String roleName, @RequestParam(name="flag",defaultValue="0")Integer flag,
                       @RequestParam(value = "pn",defaultValue = "1") Integer pageNum,
                       @RequestParam(name = "pSize", defaultValue = "5") Integer pageSize, Model model){
        Map<String, Object> params = new HashMap<>();
        params.put("userName",userName);
        params.put("roleName",roleName);
        params.put("flag",flag);
        model.addAttribute("page", PageHelper.startPage(pageNum,pageSize));
        model.addAttribute("users", userService.findUserRoles(params));
        model.addAttribute("roles", roleService.findRoleColumns());
        return "user/list";
    }

    /**
     * 分配用户角色
     * @param userId
     * @param roleId
     * @return
     */
    @RequiresRoles("0")
    @RequiresPermissions("user:list")
    @RequestMapping(value = "/assignUserRole",method = RequestMethod.POST)
    @ResponseBody
    public String editUserGrade(@NotBlank(message = "{user.userid.notblank}") @Pattern(regexp = "^([1-9][0-9]*){1,2}$",message = "{user.userid.notblank}") String userId,
                                @NotBlank(message = "{user.userroleid.notblank}") @Pattern(regexp = "^([1-9][0-9]*){1,2}$",message = "{user.userroleid.notblank}") String roleId){
        return userService.assignUserRole(Integer.parseInt(roleId),Integer.parseInt(userId))?"success":"fail";
    }


    /**
     * 修改密码页面跳转
     * @return
     */
    @RequestMapping(value = "/editPwd",method = RequestMethod.GET)
    public String toEditPwd(){
        return "user/editPwd";
    }

    /**
     * 修改密码
     * @param userPassword
     * @param br
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/editPwd",method = RequestMethod.POST)
    public String editPwd(@Valid UserPassword userPassword, BindingResult br, HttpSession session, Model model){
        ValidationUtil.validateData(br);
        if ("success".equals(this.confirminitPwd(userPassword.getInitPassword()))) {
            if (!userPassword.compareNewPassword()) {
                if (userPassword.compareConfirmPassword()) {
                    //进行盐值加密
                    EncryptedData encryptedData = EncryptDataUtil.encryptPasswrod(userPassword.getNewPassword());
                    UserParam user = new UserParam((String) session.getAttribute("username"), encryptedData.getEncryptedPwd(),encryptedData.getSalt());
                    userService.editUserPassword(user);
                    //重新设置subject保存对象中的值
                    UserFind u = (UserFind)SecurityUtils.getSubject().getPrincipal();
                    u.setUserPassword(encryptedData.getEncryptedPwd());
                    u.setSalt(encryptedData.getSalt());
                    return "success";
                }
                model.addAttribute("msg","两次输入密码不一致");
            }else {
                model.addAttribute("msg","新密码与原密码一致");
            }
        } else {
            model.addAttribute("msg","原密码输入不正确");
        }
        return "user/editPwd";
    }

    /**
     * 用户信息删除
     * @param id
     * @return
     */
    @RequiresRoles("0")
    @RequiresPermissions("user:list")
    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @ResponseBody
    public String removeUser(Integer id){
        return this.userService.removeUser(id)?"success":"fail";
    }

    /**
     * 用户信息恢复
     * @param id
     * @return
     */
    @RequiresRoles("0")
    @RequiresPermissions("user:list")
    @RequestMapping(value = "/recover",method = RequestMethod.POST)
    @ResponseBody
    public String recoverUser(Integer id){
        return this.userService.recoverUser(id)?"success":"fail";
    }

    /**
     * 用户信息批量删除
     * @param ids
     * @return
     */
    @RequiresRoles("0")
    @RequiresPermissions("user:list")
    @RequestMapping(value = "/removes",method = RequestMethod.POST)
    @ResponseBody
    public String removeUsers(Integer[] ids){
        return this.userService.batchRemoveUsers(Arrays.asList(ids))?"success":"fail";
    }

    /**
     * 用户信息批量恢复
     * @param ids
     * @return
     */
    @RequiresRoles("0")
    @RequiresPermissions("user:list")
    @RequestMapping(value = "/recovers",method = RequestMethod.POST)
    @ResponseBody
    public String recoverUsers(Integer[] ids){
        return this.userService.batchRecoverUsers(Arrays.asList(ids))?"success":"fail";
    }

    /**
     * 验证用户名
     * @param userName
     * @return
     */
    @RequestMapping(value = "/confirmUsername",method = RequestMethod.POST)
    @ResponseBody
    public String confirmUsername(String userName){
        return userService.checkUserName(userName)?"success":"fail";
    }

    /**
     * 验证原密码
     * @param initPwd
     * @return
     */
    @RequestMapping(value = "/confirminitPwd",method = RequestMethod.POST)
    @ResponseBody
    public String confirminitPwd(String initPwd){
        UserFind u = (UserFind) SecurityUtils.getSubject().getPrincipal();
        String encryptPassword = new SimpleHash("md5",initPwd,u.getSalt(),3).toHex();
        return u.getUserPassword().equals(encryptPassword)?"success":"fail";
    }
}
